package com.ruoyi.media.sphxdSend.controller;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.media.forestApi.SphxdApi;
import com.ruoyi.media.sphxdSend.domain.MediaSphxdSend;
import com.ruoyi.media.utils.XStringUtils;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.media.sphxdSend.domain.vo.MediaSphxdSendVo;
import com.ruoyi.media.sphxdSend.domain.bo.MediaSphxdSendBo;
import com.ruoyi.media.sphxdSend.service.IMediaSphxdSendService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 视频号小店一键发货
 *
 * @author dqw
 * @date 2023-06-04
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/media/sphxdSend")
public class MediaSphxdSendController extends BaseController {

    private final IMediaSphxdSendService iMediaSphxdSendService;
    private final SphxdApi sphxdApi;

    /**
     * 查询视频号小店一键发货列表
     */
    @SaCheckPermission("media:sphxdSend:list")
    @GetMapping("/list")
    public TableDataInfo<MediaSphxdSendVo> list(MediaSphxdSendBo bo, PageQuery pageQuery) {
        return iMediaSphxdSendService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出视频号小店一键发货列表
     */
    @SaCheckPermission("media:sphxdSend:export")
    @Log(title = "视频号小店一键发货", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(MediaSphxdSendBo bo, HttpServletResponse response) {
        List<MediaSphxdSendVo> list = iMediaSphxdSendService.queryList(bo);
        ExcelUtil.exportExcel(list, "视频号小店一键发货", MediaSphxdSendVo.class, response);
    }


    /**
     * 视频号小店发货
     */
    @Log(title = "视频号小店一键发货", businessType = BusinessType.EXPORT)
    @PostMapping("/sendOutGood")
    public R<?> sendOutGood(@RequestBody  MediaSphxdSendBo bo) {
        LambdaQueryWrapper<MediaSphxdSend> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MediaSphxdSend::getProductId,bo.getProductId());
        List<MediaSphxdSend> mediaSphxdSendsList =  iMediaSphxdSendService.list(queryWrapper);
        for(MediaSphxdSend mediaSphxdSend : mediaSphxdSendsList){
            Map<String,Object> params = new HashMap<>();
            params.put("deliverType",3);
            params.put("orderId",mediaSphxdSend.getOrderId());

            String res = sphxdApi.sendOutGood(bo.getCookies(),params);
            JSONObject resJson = JSONObject.parseObject(res);
            if(resJson.getInteger("errcode") == 0){
                iMediaSphxdSendService.removeById(mediaSphxdSend.getId());
            }
        }
        return R.ok("获取成功！");
    }



    /**
     * 获取待发货订单数据
     *
     */
    @PostMapping("getOrderList")
    public R<?> getOrderList(@RequestBody  MediaSphxdSendBo bo) {
//        List<MediaSphxdSend> dataList = new ArrayList<>();
        Map<String,Object> params = new HashMap<>();
        params.put("token","");
        params.put("lang","zh_CN");
        params.put("pageNum",1);
        params.put("nextKey",null);
        params.put("orderStatus",20);
        params.put("startTime",bo.getStartTime().getTime() / 1000);
        params.put("endTime",bo.getEndTime().getTime() / 1000);

        String res = sphxdApi.getOrderList(bo.getCookies(),params);
        if(JSONObject.parseObject(res).getInteger("ret") == 0 ){
            int totalPage = JSONObject.parseObject(res).getInteger("totalPage"); //页数
            //下一页参数
            int count = 1;
            String nextKey = null;
            for(int j = 0 ; j < totalPage;j++){
               try{
                   int finalCount = count;
                   String encodedKey = null;
                   if(XStringUtils.isNotEmpty(nextKey)){
                       encodedKey = URLEncoder.encode(nextKey, "UTF-8");
                   }

                   //调整动态参数
                   params.put("pageNum",finalCount);
                   params.put("nextKey",encodedKey);

                   String orderData =  sphxdApi.getOrderList(bo.getCookies(),params);
                   nextKey = JSONObject.parseObject(orderData).getString("nextKey");
                   JSONObject data =  JSONObject.parseObject(orderData);
                   JSONArray orderList =  data.getJSONArray("orders");
                   for(int i = 0 ; i < orderList.size();i++){
                       JSONObject item =   (JSONObject)orderList.get(i);

                       //商品id
                      String productId =  ((JSONObject)item.getJSONArray("list").get(0)).getString("productId");

                       //实际支付价格
                       String price = item.getString("orderPrice");
                       //假设金额
                       String maxPrice = bo.getOrderPriceMax();
                       String minPrice = bo.getOrderPriceMin();

                       // 将字符串转换为 BigDecimal 类型
                       BigDecimal priceBig = new BigDecimal(price).divide(new BigDecimal(100));
                       BigDecimal maxPriceBig = new BigDecimal(maxPrice);
                       BigDecimal minPriceBig = new BigDecimal(minPrice);

                       if (priceBig.compareTo(minPriceBig) < 0 || priceBig.compareTo(maxPriceBig) > 0) {
                           System.out.println("价格不在最大和最小金额之间");
                           continue;
                       }

                       //获取订单创建时间
                       String createTime = item.getString("createTime");
                       Date date = new Date(Long.parseLong(createTime) * 1000); // 将秒转换为毫秒

                       LoginUser loginUser =  LoginHelper.getLoginUser();

                       //订单地址信息
                       JSONObject addressInfo = item.getJSONObject("addressInfo");

                       MediaSphxdSend mediaSphxdSend = new MediaSphxdSend();
                       mediaSphxdSend.setOrderCreateTime(date);
                       mediaSphxdSend.setProductId(productId);
                       mediaSphxdSend.setUserId(loginUser.getUserId());
                       mediaSphxdSend.setDeptId(loginUser.getDeptId());
                       mediaSphxdSend.setNickName(item.getString("nickName"));
                       mediaSphxdSend.setOrderId(item.getString("orderId"));
                       mediaSphxdSend.setDescTitle(item.getString("desc"));
                       //地址信息
                       mediaSphxdSend.setProvinceName(addressInfo.getString("provinceName"));
                       mediaSphxdSend.setCityName(addressInfo.getString("cityName"));
                       mediaSphxdSend.setCountyName(addressInfo.getString("countyName"));
                       mediaSphxdSend.setDetailInfo(addressInfo.getString("detailInfo"));
                       //收件人姓名
                       mediaSphxdSend.setUserName(addressInfo.getString("userName"));
                       mediaSphxdSend.setTelNumber(addressInfo.getString("telNumber"));
                       mediaSphxdSend.setPostalCode(addressInfo.getString("postalCode"));
                       //订单状态  20为待发货  30为已发货
                       mediaSphxdSend.setOrderStatus(String.valueOf(item.getInteger("status")));


                       mediaSphxdSend.setOrderPrice(priceBig.toString());
                       mediaSphxdSend.setProductPrice(item.getString("productPrice").substring(0,item.getString("productPrice").length() - 2));
                       mediaSphxdSend.setAddressAll(addressInfo.getString("provinceName") + addressInfo.getString("cityName")
                           + addressInfo.getString("countyName") + addressInfo.getString("detailInfo"));
//                    dataList.add(mediaSphxdSend);
                       iMediaSphxdSendService.save(mediaSphxdSend);
                   }
                   count ++;
               }catch (Exception e){
                   System.out.println(e.getMessage());
               }
            }
            System.out.println(count);
        }
        return R.ok("获取成功！");
    }




    /**
     * 获取视频号小店一键发货详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("media:sphxdSend:query")
    @GetMapping("/{id}")
    public R<MediaSphxdSendVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iMediaSphxdSendService.queryById(id));
    }

    /**
     * 新增视频号小店一键发货
     */
    @SaCheckPermission("media:sphxdSend:add")
    @Log(title = "视频号小店一键发货", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody MediaSphxdSendBo bo) {
        return toAjax(iMediaSphxdSendService.insertByBo(bo));
    }

    /**
     * 修改视频号小店一键发货
     */
    @SaCheckPermission("media:sphxdSend:edit")
    @Log(title = "视频号小店一键发货", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody MediaSphxdSendBo bo) {
        return toAjax(iMediaSphxdSendService.updateByBo(bo));
    }

    /**
     * 删除视频号小店一键发货
     *
     * @param ids 主键串
     */
    @SaCheckPermission("media:sphxdSend:remove")
    @Log(title = "视频号小店一键发货", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteAll")
    public R<?> remove() {
        //获取登录用户
        LoginUser loginUser = LoginHelper.getLoginUser();

        MediaSphxdSendBo bo  = new MediaSphxdSendBo();
        bo.setUserId(loginUser.getUserId());
        List<MediaSphxdSendVo>  mediaSphxdSendVoList =  iMediaSphxdSendService.queryList(bo);
        if(mediaSphxdSendVoList.size() > 0){
            List<String> listData = new ArrayList<>();
            for(MediaSphxdSendVo vo :mediaSphxdSendVoList){
                listData.add(vo.getId());
            }
            return toAjax(iMediaSphxdSendService.deleteWithValidByIds(listData, true));
        }else{
            return R.ok("没有数据！");        }
    }
}
